/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData,
  pickedLineData,
  pickedModelData,
  pickedVertexData,
} from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import {
  DefaultLawCurveValue,
  getLawCurveFromJSONString,
  isLawCurveValid,
  LawCurve,
  LawCurveButton,
} from '@app-cad/common/law-curve';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { ChildSurfaceCommandProps } from './type';

type SplineType = {
  id?: string;
  leftBound?: string;
  rightBound?: string;
};

type Params = {
  mode: string;
  profile: string;
  guide: string;
  surface: string;
  spline?: SplineType;
  solution: number;
  lineLawAngle: LawCurve;
};

type FormData = {
  profile: pickedLineData | pickedModelData;
  guide: pickedLineData;
  surface: pickedFaceData;
  jsonAngle: string;
  splineId: pickedLineData;
  leftBound: pickedVertexData;
  rightBound: pickedVertexData;
};

export function Reference({
  onClose,
  props,
  editDxid,
}: ChildSurfaceCommandProps) {
  const initData: FormData = {
    profile: null,
    guide: null,
    surface: null,
    jsonAngle: DefaultLawCurveValue,
    splineId: null,
    leftBound: null,
    rightBound: null,
  };

  const [formData, setFormData] = useState<FormData>(initData);
  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const {
      profile,
      guide,
      surface,
      splineId,
      leftBound,
      rightBound,
      jsonAngle,
    } = formData;

    const params = {
      mode: 'ReferenceSurface',
      profile: getIdOfPickedObj(profile),
      guide: guide.edgeId,
      surface: getIdOfPickedObj(surface),
      spline: {
        id: splineId?.edgeId ?? guide.edgeId,
        leftBound: leftBound ? leftBound.vertexId : undefined,
        rightBound: rightBound ? rightBound.vertexId : undefined,
      },
      lineLawAngle: getLawCurveFromJSONString(jsonAngle),
      solution: solution,
    } as Params;

    return confirmCommand({ type: 'ExplicitSweep', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { profile, guide, surface, lineLawAngle, spline } = params;
    const { id, leftBound, rightBound } = spline;

    await initEditDependency(
      [profile, guide, spline?.id, lineLawAngle?.bsplineId].filter(
        (id) => id != null,
      ),
    );

    setFormData({
      profile: picker.generatePickObjByPickID(profile) as
        | pickedLineData
        | pickedModelData,
      guide: picker.generatePickObjByPickID(guide) as pickedLineData,
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      jsonAngle: JSON.stringify(lineLawAngle),
      splineId: picker.generatePickObjByPickID(id) as pickedLineData,
      leftBound: picker.generatePickObjByPickID(leftBound) as pickedVertexData,
      rightBound: picker.generatePickObjByPickID(
        rightBound,
      ) as pickedVertexData,
    });

    setSolution(props?.params?.solution);
  }, [editDxid]);

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  useAsyncEffect(preview, [solution]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-display-draft-sweep-curve', {
      commandName: 'CreateSurface',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { profile, guide, surface, jsonAngle } = formData;
    const angleValid = isLawCurveValid(jsonAngle);
    return angleValid && profile != null && guide != null && surface != null;
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      profile: {
        type: 'string',
        format: PickInputRJSFFormat.PickSketchCurve,
      },
      guide: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
      jsonAngle: {
        title: '角度',
        type: 'string',
      },
      spline: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      leftBound: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      rightBound: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  const finalFormData = {
    ...formData,
    solution: [solution, solutionNum],
  };

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      isFormDataValid={isFormDataValid()}
      className='-mt-3'
      submitLoading={isLoading}
      onCancel={onClose}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '请输入轮廓',
          'ui:autofocus': true,
        },
        guide: {
          'ui:placeholder': '请输入引导曲线',
        },
        surface: {
          'ui:placeholder': '请输入基准面',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        jsonAngle: {
          'ui:widget': LawCurveButton,
          'ui:options': {
            suffix: '度',
          },
        },
        spline: {
          'ui:placeholder': '脊线(默认是引导线)',
        },
        leftBound: {
          'ui:placeholder': '边界1(选填)',
        },
        rightBound: {
          'ui:placeholder': '边界2(选填)',
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
